using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;

namespace HuaRongDaoGame.Models
{
    /// <summary>
    /// 华容道游戏棋盘类
    /// </summary>
    public class GameBoard
    {
        /// <summary>
        /// 棋盘宽度（格子数）
        /// </summary>
        public const int BOARD_WIDTH = 4;

        /// <summary>
        /// 棋盘高度（格子数）
        /// </summary>
        public const int BOARD_HEIGHT = 5;

        /// <summary>
        /// 棋盘上的所有方块
        /// </summary>
        public List<Block> Blocks { get; private set; }

        /// <summary>
        /// 当前选中的方块
        /// </summary>
        public Block SelectedBlock { get; private set; }

        /// <summary>
        /// 移动历史记录
        /// </summary>
        public List<MoveRecord> MoveHistory { get; private set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public GameBoard()
        {
            Blocks = new List<Block>();
            MoveHistory = new List<MoveRecord>();
            SelectedBlock = null;
        }

        /// <summary>
        /// 添加方块到棋盘
        /// </summary>
        public void AddBlock(Block block)
        {
            if (IsValidPosition(block))
            {
                Blocks.Add(block);
            }
            else
            {
                throw new ArgumentException("方块位置无效或与其他方块重叠");
            }
        }

        /// <summary>
        /// 移除方块
        /// </summary>
        public void RemoveBlock(Block block)
        {
            Blocks.Remove(block);
            if (SelectedBlock == block)
            {
                SelectedBlock = null;
            }
        }

        /// <summary>
        /// 清空棋盘
        /// </summary>
        public void Clear()
        {
            Blocks.Clear();
            MoveHistory.Clear();
            SelectedBlock = null;
        }

        /// <summary>
        /// 选择方块
        /// </summary>
        public bool SelectBlock(int x, int y)
        {
            // 清除之前的选择
            if (SelectedBlock != null)
            {
                SelectedBlock.IsSelected = false;
            }

            // 查找点击位置的方块
            SelectedBlock = Blocks.FirstOrDefault(b => b.Contains(x, y));
            
            if (SelectedBlock != null)
            {
                SelectedBlock.IsSelected = true;
                return true;
            }

            return false;
        }

        /// <summary>
        /// 取消选择
        /// </summary>
        public void DeselectBlock()
        {
            if (SelectedBlock != null)
            {
                SelectedBlock.IsSelected = false;
                SelectedBlock = null;
            }
        }

        /// <summary>
        /// 移动选中的方块
        /// </summary>
        public bool MoveSelectedBlock(int newX, int newY)
        {
            if (SelectedBlock == null)
                return false;

            // 检查是否可以移动
            if (!CanMoveBlock(SelectedBlock, newX, newY))
                return false;

            // 记录移动历史
            var moveRecord = new MoveRecord
            {
                BlockId = SelectedBlock.Id,
                FromX = SelectedBlock.X,
                FromY = SelectedBlock.Y,
                ToX = newX,
                ToY = newY,
                Timestamp = DateTime.Now
            };

            // 执行移动
            SelectedBlock.MoveTo(newX, newY);
            MoveHistory.Add(moveRecord);

            return true;
        }

        /// <summary>
        /// 检查方块是否可以移动到指定位置
        /// </summary>
        public bool CanMoveBlock(Block block, int newX, int newY)
        {
            // 检查边界
            if (!block.CanMoveTo(newX, newY, BOARD_WIDTH, BOARD_HEIGHT))
                return false;

            // 创建临时方块检查重叠
            var tempBlock = new Block(block.Id, block.Name, block.Width, block.Height, newX, newY, block.Color, block.IsCaoCao);

            // 检查与其他方块的碰撞
            foreach (var otherBlock in Blocks)
            {
                if (otherBlock != block && tempBlock.IntersectsWith(otherBlock))
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 检查位置是否有效
        /// </summary>
        public bool IsValidPosition(Block block)
        {
            // 检查边界
            if (!block.CanMoveTo(block.X, block.Y, BOARD_WIDTH, BOARD_HEIGHT))
                return false;

            // 检查与其他方块的碰撞
            foreach (var otherBlock in Blocks)
            {
                if (block.IntersectsWith(otherBlock))
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 检查游戏是否胜利
        /// </summary>
        public bool IsGameWon()
        {
            var caoCaoBlock = Blocks.FirstOrDefault(b => b.IsCaoCao);
            if (caoCaoBlock == null)
                return false;

            // 曹操方块需要到达出口（通常是右下角）
            return caoCaoBlock.X == 1 && caoCaoBlock.Y == 3;
        }

        /// <summary>
        /// 获取指定位置的方块
        /// </summary>
        public Block GetBlockAt(int x, int y)
        {
            return Blocks.FirstOrDefault(b => b.Contains(x, y));
        }

        /// <summary>
        /// 撤销上一步移动
        /// </summary>
        public bool UndoLastMove()
        {
            if (MoveHistory.Count == 0)
                return false;

            var lastMove = MoveHistory[MoveHistory.Count - 1];
            var block = Blocks.FirstOrDefault(b => b.Id == lastMove.BlockId);
            
            if (block != null)
            {
                block.MoveTo(lastMove.FromX, lastMove.FromY);
                MoveHistory.RemoveAt(MoveHistory.Count - 1);
                return true;
            }

            return false;
        }

        /// <summary>
        /// 获取棋盘状态快照
        /// </summary>
        public GameBoardSnapshot GetSnapshot()
        {
            var snapshot = new GameBoardSnapshot
            {
                Blocks = Blocks.Select(b => b.Clone()).ToList(),
                MoveHistory = new List<MoveRecord>(MoveHistory)
            };
            return snapshot;
        }

        /// <summary>
        /// 从快照恢复棋盘状态
        /// </summary>
        public void RestoreFromSnapshot(GameBoardSnapshot snapshot)
        {
            Blocks.Clear();
            Blocks.AddRange(snapshot.Blocks.Select(b => b.Clone()));
            
            MoveHistory.Clear();
            MoveHistory.AddRange(snapshot.MoveHistory);
            
            DeselectBlock();
        }

        /// <summary>
        /// 获取所有可能的移动方向
        /// </summary>
        public List<Point> GetPossibleMoves(Block block)
        {
            var possibleMoves = new List<Point>();
            
            // 检查四个方向
            var directions = new[] { 
                new Point(-1, 0), // 左
                new Point(1, 0),  // 右
                new Point(0, -1), // 上
                new Point(0, 1)   // 下
            };

            foreach (var direction in directions)
            {
                int newX = block.X + direction.X;
                int newY = block.Y + direction.Y;
                
                if (CanMoveBlock(block, newX, newY))
                {
                    possibleMoves.Add(new Point(newX, newY));
                }
            }

            return possibleMoves;
        }
    }

    /// <summary>
    /// 移动记录
    /// </summary>
    public class MoveRecord
    {
        public int BlockId { get; set; }
        public int FromX { get; set; }
        public int FromY { get; set; }
        public int ToX { get; set; }
        public int ToY { get; set; }
        public DateTime Timestamp { get; set; }
    }

    /// <summary>
    /// 棋盘状态快照
    /// </summary>
    public class GameBoardSnapshot
    {
        public List<Block> Blocks { get; set; }
        public List<MoveRecord> MoveHistory { get; set; }
    }
} 